package com.bulunsh.wensen.distributed.oauth.dao;

import com.bulunsh.wensen.distributed.oauth.model.PermissionDto;
import com.bulunsh.wensen.distributed.oauth.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public UserDto getUserByUsername(String username){
        String sql = "select id,username,password,fullname,mobile from t_user where username = ?";
       List<UserDto> list = jdbcTemplate.query(sql,new Object[]{username},new BeanPropertyRowMapper<>(UserDto.class));

       return list.get(0);
    }

    //根据用户id 查找用户权限

    public List<String> findPermissionByUser(String userId){

        String sql = "select tp.* from t_permission tp\n" +
                "LEFT JOIN t_role_permission trp on tp.id = trp.permissionid\n" +
                "LEFT JOIN t_user_role tur on tur.roleid = trp.roleid\n" +
                "where tur.id = ?";
        List<PermissionDto> list = jdbcTemplate.query(sql,new Object[]{userId},new BeanPropertyRowMapper<>(PermissionDto.class));

        List<String> permissionList = list.stream().map(PermissionDto::getCode).collect(Collectors.toList());
        return permissionList;
    }
}
